package com.qtyx.nms.ui.activity

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
import com.qtyx.nms.R
import com.qtyx.nms.mvp.model.bean.MessageBean
import com.qtyx.nms.mvp.model.bean.NurseBean
import com.qtyx.nms.mvp.model.bean.NurseGradeBean
import com.qtyx.nms.mvp.model.bean.ZhiBanBean
import com.qtyx.nms.mvp.presenter.HomePagePresenter
import com.qtyx.nms.mvp.view.HomePageView
import com.qtyx.nms.ui.adapter.NurseAdapter
import com.qtyx.nms.ui.base.BaseMVPActivity
import com.qtyx.nms.ui.fragment.MessageFragment
import com.qtyx.nms.ui.fragment.YiShiFragment
import com.qtyx.nms.ui.fragment.ZhiBanFragment
import com.qtyx.nms.util.DateUtil
import com.qtyx.nms.util.HomePageAnimUtil
import com.qtyx.nms.util.IntentKey
import com.qtyx.nms.util.shared.AppInfoShared
import kotlinx.android.synthetic.main.ac_homepage.*
import kotlinx.android.synthetic.main.l_homepage_menu.*
import java.io.Serializable
import java.util.*


/**
 * 主页
 */
class HomePageActivity : BaseMVPActivity<HomePagePresenter>(),HomePageView {
    override fun getLayoutId() = R.layout.ac_homepage
    override fun createPresenter()= HomePagePresenter(this)

    companion object{
        /**等级集合，key为等级1、2、3，value等级值*/
        val gradeMap= mutableMapOf<String,String>()
        /**等级集合，key为等级1、2、3，value等级颜色*/
        val gradeColorMap= mutableMapOf<String,String>()
        /**是否进入了消息列表**/
        var isEnterMessageList=false
    }


    override fun initData() {
        isShowBack=false
        initMenu()
        initTab()
        timedTask()

        tvHomepageHospital.text=AppInfoShared.getHospitalName()
        tvHomepageKeShi.text=AppInfoShared.getDeptName()

        //获取护理数据
        presenter.getNurseData()
        //护理等级
        presenter.getNurseGrade()

        //获取tab项的数据
        requestTabData()

    }

    /**
     * 获取tab项的数据
     */
    private fun requestTabData(){
        //获取值班信息
        presenter.getZhiBanInfo()
        //获取医师信息
        presenter.getYiShiList()
        //获取消息列表
        presenter.getMessageList()
    }


    override fun onResume() {
        super.onResume()
        if(isEnterMessageList){
            //获取消息列表
            presenter.getMessageList()
            isEnterMessageList=false
        }
    }

    /**
     * 获取一般护理数据
     */
    override fun getGeneralNurseDataSucceed(list: List<NurseBean.Data>, spanCount: Int) {
        recyclerViewGeneral.layoutManager = GridLayoutManager(mContext, spanCount)
        val adapter = NurseAdapter(mContext, list,spanCount)
        adapter.nurseItemType=1
        recyclerViewGeneral.adapter = adapter
    }
    /**
     * 获取特殊护理数据
     */
    override fun getSpecialNurseDataSucceed(list: List<NurseBean.Data>, spanCount: Int) {
        recyclerViewSpecial.layoutManager = GridLayoutManager(mContext, spanCount)
        val adapter=NurseAdapter(mContext, list,spanCount)
        adapter.nurseItemType=2
        recyclerViewSpecial.adapter = adapter
    }

    /**
     * 获取护理等级颜色成功
     */
    override fun getNurseGradeSucceed(list: List<NurseGradeBean.Data>) {
        for (data in list) {
            gradeMap[data.dictLabel]=data.dictValue
            gradeColorMap[data.dictLabel]=data.remark
        }
    }

    /**
     * 获取值班信息成功
     */
    override fun getZhiBanInfoSucceed(list: List<ZhiBanBean.Data>) {
        window.decorView.postDelayed({
            //UI线程更新
            runOnUiThread{
                if(list.isNotEmpty()){
                    zhiBanFragment.setData(list[0].contents)
                }else{
                    zhiBanFragment.setData("")
                }
            }
        }, 500)
    }

    /**消息集合，点击菜单消息，进入列表需要传值**/
    private var listMessage=ArrayList<MessageBean.Data>()

    /**
     * 获取消息成功
     */
    override fun getMessageSucceed(list: List<MessageBean.Data>) {
        window.decorView.postDelayed({
            //UI线程更新
            runOnUiThread{
                messageFragment.setData(list)
            }
        }, 500)

        if(list.isNotEmpty()){
            listMessage= list as ArrayList<MessageBean.Data>
            val count=listMessage.filter { 0==it.readType }.size
            if(count>0){
                tvHomepageTabMessageCount.text=count.toString()
                tvHomepageTabMessageCount.visibility=View.VISIBLE
            }else{
                tvHomepageTabMessageCount.visibility=View.GONE
            }
        }else{
            tvHomepageTabMessageCount.visibility=View.GONE
        }
    }

    /**
     * 获取医师列表成功
     */
    override fun getYiShiSucceed(list: List<NurseBean.Data>) {
        window.decorView.postDelayed({
            //UI线程更新
            runOnUiThread{
                yiShiFragment.setData(list)
            }
        }, 500)
    }

    //============================================初始化Tab（今日值班、消息中心）========================================================
    private val zhiBanFragment = ZhiBanFragment()
    private val yiShiFragment = YiShiFragment()
    private val messageFragment = MessageFragment()
    /**
     * 初始化Tab
     */
    private fun initTab() {
        //默认选中第一个
        tvHomepageTabJrzb.isSelected = true
        viewTabJrzbLine.visibility = View.VISIBLE

        val listFragments = mutableListOf<Fragment>()
        listFragments.add(zhiBanFragment)
        listFragments.add(yiShiFragment)
        listFragments.add(messageFragment)
        val adapter = MainFrameAdapter(supportFragmentManager, listFragments)
        vpContent.adapter = adapter
        vpContent.offscreenPageLimit=2
        vpContent.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int,positionOffset: Float,positionOffsetPixels: Int) {}
            override fun onPageScrollStateChanged(state: Int) {}
            override fun onPageSelected(position: Int) {
                viewPagerPeriodSecond=0
                when(position){
                    0->{
                        tvHomepageTabJrzb.isSelected = true
                        tvHomepageTabYiShi.isSelected = false
                        tvHomepageTabMessage.isSelected = false
                        viewTabJrzbLine.visibility = View.VISIBLE
                        viewTabMessageYiShi.visibility=View.INVISIBLE
                        viewTabMessageLine.visibility = View.INVISIBLE
                    }
                    1->{
                        tvHomepageTabJrzb.isSelected = false
                        tvHomepageTabYiShi.isSelected = true
                        tvHomepageTabMessage.isSelected = false
                        viewTabJrzbLine.visibility = View.INVISIBLE
                        viewTabMessageYiShi.visibility=View.VISIBLE
                        viewTabMessageLine.visibility = View.INVISIBLE
                    }
                    2->{
                        tvHomepageTabJrzb.isSelected = false
                        tvHomepageTabYiShi.isSelected = false
                        tvHomepageTabMessage.isSelected = true
                        viewTabJrzbLine.visibility = View.INVISIBLE
                        viewTabMessageYiShi.visibility=View.INVISIBLE
                        viewTabMessageLine.visibility = View.VISIBLE
                    }
                }
            }
        })
        tvHomepageTabJrzb.setOnClickListener {
            vpContent.currentItem = 0
        }
        tvHomepageTabYiShi.setOnClickListener {
            vpContent.currentItem = 1
        }
        tvHomepageTabMessage.setOnClickListener {
            vpContent.currentItem = 2
        }
    }

    /**
     * 主界面FragmentViewPage适配器
     */
    class MainFrameAdapter(
        fm: FragmentManager,
        private val listFragments: List<Fragment>
    ) :
        FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT),
        Serializable {
        override fun getItem(position: Int): Fragment {
            return listFragments[position]
        }
        override fun getCount(): Int {
            return listFragments.size
        }
    }





    //============================================初始化菜单操作========================================================
    /**是否打开菜单**/
    private var isOpenMenu=false
    /**是否可以点击，防止快速点击**/
    private var isSwitchClick=true

    /**
     * 菜单操作
     */
    private fun initMenu(){
        //动画操作
        HomePageAnimUtil.menuSwitchLayout=flHomePageMenu
        HomePageAnimUtil.menuSwitchImageView=ivHomePageMenu
        HomePageAnimUtil.menuView=clHomePageMenu
        //首次进入关闭菜单
        window.decorView.post {
            HomePageAnimUtil.menuIsOpenMenu(false)
        }

        //点击菜单开关
        flHomePageMenu.setOnClickListener {
            if(isSwitchClick){
                isSwitchClick=false
                
                //是否打开菜单
                isOpenMenu=!isOpenMenu
                HomePageAnimUtil.menuIsOpenMenu(isOpenMenu)
                
                //防止重复点击，菜单动画结束才能点击
                window.decorView.postDelayed({isSwitchClick=true},HomePageAnimUtil.duration*2)
                
                //重置菜单关闭秒数
                if(isOpenMenu){
                    menuCloseSecond=0
                }
            }
        }
        llMenuMessage.setOnClickListener {
            isEnterMessageList=true
            val bundle=Bundle()
            bundle.putParcelableArrayList(IntentKey.messageList, listMessage)
            bundle.putInt(IntentKey.messageSelectPosition,0)
            startActivityCustom(MessageListActivity::class.java,bundle)
        }
        llMenuLogout.setOnClickListener {
            AppInfoShared.saveUserPassword("")
            startActivityAndFinish(LoginActivity::class.java)
        }
        llMenuSetting.setOnClickListener {
            startActivityCustom(SettingActivity::class.java)
        }
    }


    //============================================定时器========================================================
    /**消息请求周期，按秒+1**/
    var messageRequestSecond:Int=0
    /**护理请求周期，按秒+1**/
    var nurseRequestSecond:Int=0
    /**tab切换周期，按秒+1**/
    var viewPagerPeriodSecond:Int=0
    /**菜单自动收起，按秒+1**/
    var menuCloseSecond:Int=0

    /**时间戳，用于展示时间**/
    var timestamp:Long=0
    /**
     * 根据后台返回的时间，转成时间显示
     */
    private fun timedTask() {
        //获取后台时间戳，为空，则用本机时间戳
        timestamp=if(AppInfoShared.getServerDate()!=0L)AppInfoShared.getServerDate()else System.currentTimeMillis()

        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    timestamp+=1000
                    val ymd=DateUtil.getDate2String(timestamp,"yyyy年MM月dd日")
                    val hms=DateUtil.getDate2String(timestamp,"HH:mm:ss")
                    val week=DateUtil.getWeek(timestamp)
                    tvHomePageDate.text= "$ymd $week $hms"

                    //获取tab项的数据
                    messageRequestSecond++
                    if(messageRequestSecond>10){
                        messageRequestSecond=0
                        requestTabData()
                    }

                    //菜单关闭
                    menuCloseSecond++
                    if(menuCloseSecond>15){
                        menuCloseSecond=0

                        //如果开关按钮打开了
                        if(isOpenMenu){
                            isOpenMenu=false
                            HomePageAnimUtil.menuIsOpenMenu(isOpenMenu)
                        }
                    }

                    //获取护理数据
                    nurseRequestSecond++
                    if(nurseRequestSecond>30){
                        nurseRequestSecond=0
                        presenter.getNurseData()
                    }


                    //是否自动轮播
                    if(AppInfoShared.getTabAutoLunBo()){
                        viewPagerPeriodSecond++
                        if(viewPagerPeriodSecond>AppInfoShared.getTabAutoLunBoTime()*60){
                            vpContent.currentItem=(vpContent.currentItem+1)%3
                        }
                    }
                }
            }
        }, 0, 1000)
    }

    private var timer: Timer?=null

    override fun onDestroy() {
        timer?.cancel()
        super.onDestroy()
    }


}
